﻿/*
 * Create By：Steven Jiang 
 * Create Date：2010-3-12
 * 
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.Persistent;
using System.Data;

public partial class ThirdPartyPersonEdit : PageBase
{
    protected String PostURL;
    private decimal? id = null;
    private Person _person;
    private PersonManager manager = new PersonManager();
    private Boolean ReadOnly;
    protected void Page_Load(object sender, EventArgs e)
    {

        PostURL = "ThirdPartyPersonEdit.ashx?" + Request.QueryString.ToString();
        if (!string.IsNullOrEmpty(Request["id"]))
        {

            try
            {
                id = decimal.Parse(Request["id"]);
            }
            catch { }

        }
        if (Request.Form.Count > 0)
        {
            Save();
        }
        else if (!IsPostBack)
        {
            DataBind();
            //如果txtJoinDate被置为无效状态，则验证控件也必须无效
            if (txtJoinDate.Disabled)
                rv1.Enabled = false;
            //设置最大时间
            rv1.MaximumValue = DateTime.Now.ToString("yyyy-MM-dd");
            rv1.MinimumValue = "1990-01-01";

            BindDDL();

            if (!string.IsNullOrEmpty(Request["id"]) && id != null)
            {
                _person = manager.Load(id.Value);
                if (_person != null)
                {

                    txtCode.Disabled = true;
                    txtCode.Value = _person.Code;

                    txtIdentity.Text = _person.Identity;
                    txtName.Value = _person.Name;
                    ddlPosition.SelectedValue = _person.Position;
                    this.ddlPosition.SelectedValue = _person.Position;
                    txtTelephone.Value = _person.Telephone;
                    txtFax.Value = _person.FAX;
                    chkValid.Checked = _person.ACTIVE;
                    txtMail.Value = _person.EMAIL;
                    ddlSex.Value = _person.Sex;
                    btnCancel.HRef = String.Format("thirdpartypersonlist.aspx?{0}", _person.OrgID);
                }
            }
            else
            {
                btnCancel.HRef = String.Format("thirdpartypersonlist.aspx?{0}", Request.QueryString.ToString());
            }
            BindManager();
            if (_person != null)
            {
                ddlManager.SelectedValue = _person.MANAGERID.ToString();
            }
            if (ReadOnly)
            {
                btnSave.Visible = false;
            }
        }


    }




    private void BindManager()
    {
        string selfid = "-1";
        if (_person != null)
            selfid = _person.ID.ToString();
        //查找第三方公司
        DataTable ot = null;
        if (_person == null)
            ot = new PersonManager().LoadByOrganizationID(int.Parse(Request.QueryString.ToString()), true, selfid, 2).BillDataTable;
        else
            ot = new PersonManager().LoadByOrganizationID(_person.OrgID, true, selfid, 2).BillDataTable;

        ddlManager.DataSource = ot;
        ddlManager.DataTextField = "NAME";
        ddlManager.DataValueField = "ID";
        ddlManager.DataBind();
        
        ddlManager.Items.Insert(0, new ListItem("--请选择--", ""));
    }

    protected void BindDDL()
    {
        DictionaryItemsManager dim = new DictionaryItemsManager();
        ddlPosition.DataSource = dim.GetItemList(DictionaryEnum.UserPosition, MyStateManager.DomainID);
        ddlPosition.DataBind();
        ddlPosition.Items.Insert(0, new ListItem("--请选择--"));

    }

    private void Save()
    {
        string year = null, month = null, day = null;
        //身份证号码是否正确
        if (!string.IsNullOrEmpty(Request.Form["txtIdentity"]))
        {

            if (txtIdentity.Text.Length == 18)
            {
                //截取年份
                year = Request.Form["txtIdentity"].Substring(6, 4);
                //截取月份
                month = Request.Form["txtIdentity"].Substring(10, 2);
                //截取日
                day = Request.Form["txtIdentity"].Substring(12, 2);
            }
            else
            {
                //截取年份
                year = "19" + Request.Form["txtIdentity"].Substring(6, 2);
                //截取月份
                month = Request.Form["txtIdentity"].Substring(8, 2);
                //截取日
                day = Request.Form["txtIdentity"].Substring(10, 2);
            }

            try
            {
                new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
            }
            catch
            {
                Response.Write("身份证号码错误");
                return;
            }
        }


        System.Text.StringBuilder logcontent = new System.Text.StringBuilder();
        //是否新增
        bool isAdd = string.IsNullOrEmpty(Request["id"]);

        ////判断员工编号是否重复
        if (isAdd)
        {
            bool exist = manager.ExistCode(MyStateManager.DomainID, Request.Form["txtCode"], false);
            if (exist)
            {
                Response.Write("员工编号被使用，不能被再次使用");
                return;
            }
        }


        if (isAdd)
        {
            _person = new Person();
            _person.DOMAINID = MyStateManager.DomainID;
            _person.Code = Request.Form["txtCode"];
            _person.Type = 2;
            _person.OrgID = int.Parse(Request.QueryString.ToString());
        }
        else
        {
            _person = manager.Load(id.Value);

            logcontent.Append("<b>修改前条目信息</b><br /> ");
            logcontent.Append(" 姓名:" + _person.Name);
            logcontent.Append(" 编号:" + _person.Code);
            logcontent.Append(" 电话:" + _person.Telephone);
            logcontent.Append(" 传真:" + _person.FAX);
            logcontent.Append(" 电子邮箱:" + _person.EMAIL);
            logcontent.Append(" 身份证号:" + _person.Identity);
            logcontent.Append(" 电子邮箱:" + _person.EMAIL);
            logcontent.Append(" 状态 " + (_person.ACTIVE ? "有效" : "失效"));
            logcontent.Append(" 原更新人:" + _person.LAST_UPDATER);
        }
        _person.Name = Request.Form["txtName"];
        //更新User 这张表里面的ORG
        if (id != null)
        {
            var userManager = new UserManager();
            var user = userManager.GetUserByPersonID(id.Value);
            if (user != null)
            {
                user.ORGID = _person.OrgID;
                userManager.Save(user);
            }
        }
        _person.Telephone = Request.Form["txtTelephone"];
        _person.FAX = Request.Form["txtFax"];
        _person.EMAIL = Request.Form["txtMail"];
        _person.Sex = Request.Form["ddlSex"];
        if (ddlPosition.SelectedIndex > 0)
            _person.Position = ddlPosition.SelectedValue;
        _person.Identity = Request.Form["txtIdentity"];
        _person.Type = 1;
        _person.ACTIVE = Request.Form["chkValid"].Equals("on");
        _person.LAST_UPDATER = MyStateManager.Name;
        if (ddlManager.SelectedIndex > 0)
        {
            _person.MANAGERID = decimal.Parse(ddlManager.SelectedValue);
        }
        try
        {
            manager.Save(_person);

        }
        catch (Exception ex)
        {

            ShowMessage("操作失败，错误已经记录日志");
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(
                Jumpton.SFA.Server.BusinessRule.System.LogType.GENERAL_EXCEPTION, this.MyStateManager.Name,
                this.MyStateManager.UserID, "人员维护 - 异常:" + ex.Message);
            return;
        }

        if (isAdd)
        {
            logcontent.Append("<br /><b>新增条目信息:</b>");

        }
        else
        {
            logcontent.Append("<br />修改后条目信息:<br />");
        }

        logcontent.Append(" 姓名:" + _person.Name);
        logcontent.Append(" 电话:" + _person.Telephone);
        logcontent.Append(" 传真:" + _person.FAX);
        logcontent.Append(" 电子邮箱:" + _person.EMAIL);
        logcontent.Append(" 身份证号:" + _person.Identity);
        logcontent.Append(" 状态 " + (_person.ACTIVE ? "有效" : "失效"));

        if (isAdd)
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change,
                MyStateManager.Name, MyStateManager.UserID.ToString(), "新增人员信息:" + _person.Name, logcontent.ToString());
        }
        else
        {
            Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.Info_Change,
               MyStateManager.Name, MyStateManager.UserID.ToString(), "字人员信息更改:" + _person.Name, logcontent.ToString());
        }

        //跳转到主界面
        Response.Redirect(btnCancel.HRef);
    }
    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {

        Save();

    }


    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        BindManager();
    }
}
